<script lang="ts" setup>
import dayjs from 'dayjs'
import { goodsSkuListDeleteList, goodsSkuListModifyList } from '@/api/goodsSkuList'
import { myGoodsDetail, myGoodsList } from '@/api/goods'
import type { GoodsItemModel, GoodsItemskuListModel, MyGoodsListSendModel } from '@/api/goods'
import { setSku_list, setSpec_list } from '@/views/goods/set_Sku_data'
import type { SkuListItem, SpecListItem } from '@/views/goods/set_Sku_data'
import type { CategoryGetReturnItemModel } from '@/api/category'
import { categoryGetTwo } from '@/api/category'

interface GoodsItemTableModel extends GoodsItemModel {
  sku_list?: SkuListItem[]
  spec_list?: SpecListItem[]
}
/** 初始化数据 */
const tableData = ref<GoodsItemTableModel[]>([])
const listQuery = ref<MyGoodsListSendModel>({
  page: 1,
  size: 10,
  total: 0,
})
async function getList() {
  const { code, data } = await myGoodsList(listQuery.value)
  if (code === 0) {
    listQuery.value.total = data.total
    tableData.value = data.list

    let flag = 0
    for (let i = 0; i < tableData.value.length; i++) {
      myGoodsDetail({ goodsId: tableData.value[i].id }).then(({ code, data }) => {
        if (code === 0) {
          tableData.value[i] = data
          tableData.value[i].sku_list = setSku_list(data, data.none_sku ? 'none' : '')
          tableData.value[i].spec_list = setSpec_list(data.skuList, data.none_sku ? 'none' : '')
          flag++
          if (flag === tableData.value.length)
            console.log(tableData.value, listQuery.value, '商品数据')
        }
      })
    }
  }
}

/** 表格分类回显文字部分 */
const categoryTwoData = ref<CategoryGetReturnItemModel[]>()
async function getCategoryTwo() { // 获取二级分类
  const { data, code } = await categoryGetTwo()
  if (code === 0)
    categoryTwoData.value = data
}
function categoryFilter(parentId: number | string) {
  if (categoryTwoData.value?.length === 0)
    return '空'
  let categoryName = ''
  categoryTwoData.value?.forEach((item) => {
    if (item.id === parentId)
      categoryName = item.name
  })
  return categoryName
}
/** 对话框 */
interface SkuValue {
  [propName: string]: any
}
interface Dialog {
  visible: boolean
  title: string

  id?: number | string
  goodsId: number | string
  price: number | null
  stock_num: number | null

  goodsItem: GoodsItemTableModel | null
  skuValue: SkuValue
}
const dialog = ref<Dialog>({
  visible: false,
  title: '',

  id: '', // sku列表id
  goodsId: '', // 当前商品 id
  price: null, // 该sku列表价格
  stock_num: null, // 该sku列表库存
  goodsItem: null, // 单个商品数据
  skuValue: {}, // 选择的sku列表id
})
function openDialog(goodsItem: GoodsItemTableModel, type: string, skuListItem?: SkuListItem) { // 打开对话框
  dialog.value.visible = true
  switch (type) {
    case 'add':
      dialog.value.title = '添加规格列表'
      dialog.value.goodsId = goodsItem.id
      dialog.value.goodsItem = goodsItem
      break
    case 'modify':
      dialog.value.title = '修改规格列表'
      dialog.value.goodsId = goodsItem.id
      dialog.value.goodsItem = goodsItem
      dialog.value.id = skuListItem?._id
      dialog.value.price = Number(skuListItem?.price)
      dialog.value.stock_num = Number(skuListItem?.stock)

      // 确定sku id
      skuListItem?.indexList.forEach((item) => {
        goodsItem.skuList[item.parentIndex].vId = goodsItem.skuList[item.parentIndex].v[item.sonIndex].id
        dialog.value.skuValue[goodsItem.skuList[item.parentIndex].k_s] = goodsItem.skuList[item.parentIndex].v[item.sonIndex].id
      })
      break
  }
}
function closeDialog() { // 关闭对话框
  dialog.value = {
    visible: false,
    title: '',

    id: '', // sku列表id
    goodsId: '', // 当前商品 id
    price: null, // 该sku列表价格
    stock_num: null, // 该sku列表库存
    goodsItem: null, // 单个商品数据
    skuValue: {}, // 选择的sku列表id
  }
}
async function submitDialog() { // 提交表单
  if (!dialog.value.stock_num) {
    window.$message?.warning('请输入该选项库存')
    return
  }
  if (!dialog.value.price) {
    window.$message?.warning('请输入该选项价格')
    return
  }
  if (Object.keys(dialog.value.skuValue).length !== dialog.value.goodsItem?.skuList.length) {
    window.$message?.warning('请选择规格列表')
    return
  }
  const { code, msg } = await goodsSkuListModifyList({
    id: dialog.value.id ? dialog.value.id : undefined,
    parentId: dialog.value.goodsId,
    price: dialog.value.price,
    stock_num: dialog.value.stock_num,
    ...dialog.value.skuValue,
  })
  if (code === 0) {
    window.$message?.success(msg)
    getList()
    closeDialog()
  }
}
function radioGroupSkuList(item: GoodsItemskuListModel, vId: number) { // 单选框规格回调
  dialog.value.skuValue[item.k_s] = vId
}

/** 删除sku列表item */
async function removeSkuListItem(id: number) {
  window.$dialog?.warning({
    title: '提示',
    content: '确定执行此操作吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { code, msg } = await goodsSkuListDeleteList({ ids: id.toString() })
      if (code === 0) {
        window.$message?.success(msg)
        getList()
      }
    },
  })
}
onMounted(() => {
  getList()
  getCategoryTwo()
})
</script>

<template>
  <AppPage>
    <n-grid x-gap="15" :cols="8" bg-white p-10 text-14 b-rd-5 dark:bg-dark mb-20>
      <n-gi f-c-c font-bold>
        上架时间
      </n-gi>
      <n-gi f-c-c font-bold>
        商品封面
      </n-gi>
      <n-gi f-c-c font-bold>
        商品名称
      </n-gi>
      <n-gi f-c-c font-bold>
        商品标签
      </n-gi>
      <n-gi f-c-c font-bold>
        商品类别
      </n-gi>
      <n-gi f-c-c font-bold>
        商品库存
      </n-gi>
      <n-gi f-c-c font-bold>
        规格信息
      </n-gi>
      <n-gi f-c-c font-bold>
        操作
      </n-gi>
    </n-grid>
    <n-collapse>
      <n-collapse-item v-for="item in tableData" :key="item.id" :name="item.id" bg-white dark:bg-dark>
        <template #header>
          <n-grid x-gap="15" :cols="8">
            <n-gi f-c-c font-bold>
              {{ dayjs(item.createTime || new Date()).format('YYYY-MM-DD HH:mm') }}
            </n-gi>
            <n-gi f-c-c font-bold>
              <Cimage
                width="50"
                height="50"
                :src="item.iconId[0].url"
              />
            </n-gi>
            <n-gi f-c-c font-bold>
              <n-ellipsis :line-clamp="1">
                {{ item.name || '未填写' }}
              </n-ellipsis>
            </n-gi>
            <n-gi f-c-c font-bold>
              <n-tag :bordered="false">
                {{ item.hot }}
              </n-tag>
            </n-gi>
            <n-gi f-c-c font-bold>
              {{ categoryFilter(item.parentId) }}
            </n-gi>
            <n-gi f-c-c font-bold>
              {{ item.stock_num }}
            </n-gi>
            <n-gi f-c-c font-bold>
              <n-tag v-if="item.none_sku" type="error">
                无规格商品
              </n-tag>
              <n-tag v-else type="info">
                多规格商品
              </n-tag>
            </n-gi>
            <n-gi f-c-c>
              <n-button type="info" size="small" text-14 ml-5 mt5 :disabled="item.none_sku ? true : false" @click.stop="openDialog(item, 'add')">
                <template #icon>
                  <icon-material-symbols:add />
                </template>
                添加规格列表
              </n-button>
            </n-gi>
          </n-grid>
        </template>
        <template #default>
          <template v-if="item.none_sku">
            <div flex items-center pb-10 ml-20 pt-10>
              无规格商品
            </div>
          </template>
          <template v-else>
            <div v-for="(value, idx) in item.sku_list" :key="value._id" flex items-center pb-10 ml-20 pt-10>
              <span>{{ idx + 1 }} 、</span>
              <Cimage :src="value.image" width="50" height="50" />
              <span text-16 ml-20>{{ value.sku_name_arr.toString() }}</span>
              <span text-16 ml-20>库存: x{{ value.stock }}</span>
              <span text-16 ml-20>价格: ￥{{ value.price }}</span>
              <n-button strong secondary type="info" ml-20 @click="openDialog(item, 'modify', value)">
                修 改
              </n-button>
              <n-button strong secondary type="error" ml-20 @click="removeSkuListItem(value._id)">
                删 除
              </n-button>
            </div>
          </template>
        </template>
      </n-collapse-item>
    </n-collapse>
    <Cpagination
      v-model:page="listQuery.page"
      :total="listQuery.total"
      :page-size="listQuery.size"
      @update-page="getList"
    />
  </AppPage>
  <Cdialog v-model:visible="dialog.visible" :title="dialog.title">
    <n-form
      ref="ModifuSkuListDialogRef"
      size="medium"
      label-placement="top"
      :model="dialog"
      :show-require-mark="true"
    >
      <n-form-item label="选项库存">
        <n-input-number v-model:value="dialog.stock_num" :show-button="false" placeholder="输入该选项库存" w-full />
      </n-form-item>
      <n-form-item label="选项价格">
        <n-input-number v-model:value="dialog.price" :show-button="false" placeholder="输入该选项价格" w-full />
      </n-form-item>
      <n-form-item v-for="item in dialog.goodsItem?.skuList" :key="item.id" :label="item.k">
        <n-radio-group v-model:value="item.vId" name="name" :on-update:value="(vId: number) => { radioGroupSkuList(item, vId) }">
          <n-radio-button
            v-for="song in item.v"
            :key="song.id"
            :value="song.id"
            :label="song.name"
          />
        </n-radio-group>
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space align="center" justify="center">
        <n-button b-rd-5 size="medium" @click="closeDialog">
          <n-icon cursor-pointer size="16">
            <icon-mdi:cancel />
          </n-icon>
          <span ml-2>取 消</span>
        </n-button>
        <n-button b-rd-5 type="primary" size="medium" @click="submitDialog">
          <n-icon cursor-pointer size="16">
            <icon-mdi:checkbox-marked-circle-outline />
          </n-icon>
          <span ml-2>确 定</span>
        </n-button>
      </n-space>
    </template>
  </Cdialog>
</template>

<style lang="scss" scoped>
:deep(.n-collapse-item) {
  .n-collapse-item__header{
    padding: 16px 0;
  }
}
:deep(.n-collapse .n-collapse-item:first-child > .n-collapse-item__header) {
  padding-top: 0;
}
:deep(.n-tag__content) {
  display: flex;
  align-items: center;
}
</style>
